﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DTO;

namespace DAO
{
    public class DoanDuongDAO : DataProvider
    {
        protected override object GetDataFromDataRow(DataTable dt, int i)
        {


            DoanDuongDTO objectDTO = new DoanDuongDTO();
            objectDTO.MaDoanDuong = int.Parse(dt.Rows[i]["MaDoanDuong"].ToString());
            objectDTO.DiaDiemDau = int.Parse(dt.Rows[i]["DiaDiemDau"].ToString());
            objectDTO.DiaDiemCuoi = int.Parse(dt.Rows[i]["DiaDiemCuoi"].ToString());
            objectDTO.KhoangCach = float.Parse(dt.Rows[i]["KhoangCach"].ToString());
            objectDTO.ThoiGianChay = dt.Rows[i]["ThoiGianChay"].ToString();
            return (object)objectDTO;
        }

        public DoanDuongDTO[] GetAll()
        {
            String strSQL = "Select * from DoanDuong ";
            DataTable dt = new DataProvider().ExecuteQuery(strSQL);

            DoanDuongDTO[] doanduongDTOs = new DoanDuongDTO[dt.Rows.Count];
            for (int i = 0; i < dt.Rows.Count; i++)
                doanduongDTOs[i] = (DoanDuongDTO)GetDataFromDataRow(dt, i);

            return doanduongDTOs;
        }

        public int insert(int diadiemdau, int diadiemcuoi)
        {
            String strSQL = "Select MaDoan from DoanDuong where DiaDiemDau='" + diadiemdau + "' and DiaDiemCuoi='" + diadiemcuoi + "' ";
            DataTable dt1 = new DataProvider().ExecuteQuery(strSQL);
            if (dt1.Rows.Count > 0)
                return int.Parse(dt1.Rows[0][0].ToString());
            else
            {
                string insertCommand = "INSERT DOANDUONG(DiaDiemDau,DiaDiemCuoi) VALUES('" +
                    diadiemdau + "', '" +
                    diadiemcuoi + "')";
                ExecuteNonQuery(insertCommand);
                string sql = "select max(MaDoan) from DOANDUONG";
                DataTable dt = new DataProvider().ExecuteQuery(sql);
                return int.Parse(dt.Rows[0][0].ToString());
            }
        }

        public void update(DoanDuongDTO info)
        {
            string updateCommand = "UPDATE DoanDuong " +
                                    "SET DiaDiemDau = '" + info.DiaDiemDau + "', " +
                                    " DiaDiemCuoi = '" + info.DiaDiemCuoi + "', " +
                                    " KhoangCach = '" + info.KhoangCach + "', " +
                                    " ThoiGianChay = '" + info.ThoiGianChay + "'" +
                                    " WHERE MaDoanDuong = " + info.MaDoanDuong;


            ExecuteNonQuery(updateCommand);
        }

        public void delete(string MaDoanDuong)
        {
            string deleteCommand = "DELETE FROM DoanDuong WHERE MaDoanDuong= " + MaDoanDuong;
            ExecuteNonQuery(deleteCommand);
        }
    }
}
